import {
  parseToCssJSONStyleData,
  toHump,
} from '@/types/modules/editor/server/code-transformer/utils/css-utils';
import { toCSS, toJSON } from 'cssjson';

export function checkCharacterNoStartWithACharacter(input) {
  if (!input) return false;
  const trimmedInput = input.trim();
  const firstChar = trimmedInput.charAt(0);
  const punctuationRegex = /[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/;
  return !punctuationRegex.test(firstChar);
}
export function checkSeparatorInString(str) {
  if (!str) return false;
  // 使用正则表达式匹配空格、大于号和选择器分隔符
  const regex = /\s|>|[+~\[\]:]/;
  // 判断字符串中间位置是否存在分隔符
  return regex.test(str.slice(1, -1));
}
export function replaceSeparators(str) {
  if (!str) return false;
  // 使用正则表达式匹配空格、大于号和选择器分隔符
  const regex = /\s|>|[+~\[\]:]/g;
  // 将匹配到的分隔符替换为"___"
  return str.replace(regex, '___');
}
export const isRoot = (input) => {
  if (!input) return false;
  if (checkSeparatorInString(input)) return false;
  return checkCharacterNoStartWithACharacter(input) || ['.', '#'].includes(input.trim()[0]);
};
export function selectorToClassname(selector) {
  // 注意: 如果不是合法的rootSelector则返回null
  if (!isRoot(selector)) return null;
  const rootSelector = selector.replace('.', '').replace('#', '');
  return rootSelector;
}

export function checkIsMedia(input) {
  return input?.trim()[0] === '@';
}

export function getCssJsonData(attributes) {
  const styleData = {};
  for (const key in attributes) {
    styleData[toHump(key)] = attributes[key];
  }
  return styleData;
}

export function parsingCss(
  cssCode,
  {
    existCssList,
  }: {
    existCssList?: any[];
  } = {},
) {
  const cssList = [];

  const cssJson = toJSON(cssCode);
  // console.log('cssJson: ', cssJson);
  const children = cssJson?.children;
  Object.keys(children)?.forEach((k) => {
    const nodeItem = children[k];
    const existItem = existCssList?.find(
      (_) => _.selector === k || selectorToClassname(_.selector) === selectorToClassname(k),
    );
    const style = getCssJsonData(nodeItem.attributes);
    const _children = Object.keys(nodeItem?.children)?.map((k) => {
      const childItem = nodeItem?.children[k];
      const existChild = existItem?.children?.find(
        (_) => _.selector === k || selectorToClassname(_.selector) === selectorToClassname(k),
      );
      const style = getCssJsonData(childItem.attributes);
      return {
        selector: k,
        style,
        title: existChild?.title,
        canvas: existChild?.canvas,
      };
    });
    cssList.push({
      selector: k,
      style,
      title: existItem?.title,
      canvas: existItem?.canvas,
      children: _children,
    });
  });
  // 转化key
  return cssList;
}
